package com.yanqu.road.server.cmd.sync;


import com.google.protobuf.AbstractMessage;
import com.google.protobuf.InvalidProtocolBufferException;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.syncMessage.SyncMessage;
import com.yanqu.road.server.cmd.CrossCommand;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.command.ICrossServiceCommand;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.protocol.GameProtocol;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.YanQuMessageUtils;

import java.util.concurrent.CompletableFuture;


@Cmd(code = Protocol.C_CROSS_SERVICE_HANDLER, desc = "同步请求处理")
public class SyncMessageCmd extends CrossCommand {

    private SyncMessage.Request request;

    @Override
    public boolean parseData(YanQuMessage packet) throws Exception {
        this.request = SyncMessage.Request.parseFrom(packet.getBytes());
        return true;
    }

    @Override
    public void execute(YanQuMessage packet) throws Exception {
        ICrossServiceCommand ICrossServiceCommand = MessageHelper.getSyncMessageProvider().getCommand(this.request.getCmdCode());
        if (ICrossServiceCommand != null) {
            try {
                SyncMessage.Response.Builder builder = SyncMessage.Response.newBuilder();
                CompletableFuture<AbstractMessage.Builder<?>> executedBuilderFuture = ICrossServiceCommand.execute(this.request);
                executedBuilderFuture.thenAccept(builder1 -> {
                    try {
                        builder.setSequenceId(request.getSequenceId());
                        builder.setRawServerId(request.getRawServerId());
                        builder.setCmdCode(request.getCmdCode());
                        builder.setDataBytes(builder1.build().toByteString());
                        builder.setActivityId(this.request.getActivityId());
                        YanQuMessage yanQuMessage = YanQuMessageUtils.buildMessage(GameProtocol.S_CROSS_SERVICE_MESSAGE_RESP, builder);
                        MessageHelper.sendPacket(this.request.getRawServerId(), this.request.getSenderId(), yanQuMessage);
                    } catch (Exception e) {
                        //e.printStackTrace();
                        log.error(e);
                        log.error("{}, code {}", ICrossServiceCommand.getClass().getSimpleName(), this.request.getCmdCode());
                    }

                });

            } catch (InvalidProtocolBufferException e) {
                log.error(e);
                log.error("{}, code {}", ICrossServiceCommand.getClass().getSimpleName(), this.request.getCmdCode());
            }
        }
    }

    @Override
    public void sendData() {

    }
}
